// pages/teacher/index.js
Page({
  data: {
    currentLocation: '', // 当前位置信息
    locationGranted: false, // 是否已获取定位权限
  latitude: null,        // 纬度
  longitude: null,       // 经度
    canGetLocation: false, // 是否有位置权限
    banners: [
      {image: '/images/banner1.jpg'},
      {image: '/images/banner2.jpg'},
      {image: '/images/banner3.jpg'}
    ],
    subjectList: ['科目','语文', '数学', '英语', '物理', '化学'],
    gradeList: ['年级', '小学', '初中', '高中', '大学'],
    distanceList: ['距离', '1公里内', '3公里内', '5公里内', '10公里内'],
    salaryList: ['薪资', '50元以下', '50-100元', '100-200元', '200元以上'],
    subjectIndex: 0,
    gradeIndex: 0,
    distanceIndex: 0,
    salaryIndex: 0,
    filteredStudents: [],
    originalStudents: [], // 保存原始学生列表
    isLoading: false,
    hasMore: true,
    currentTab: 0,
    noDataFlag: false
  },
  
  onLoad() {
    console.log('页面加载');
    // 初始化高德地图
    this.amapPlugin = new amapFile.AMapWX({
      key: '1a65b37630082ea552ad6547b8f38df4' // 替换为您的密钥
    });
    this.checkLocationPermission();
    // 添加调试信息
    console.log('初始数据:', this.data);
  },
  
  // 检查位置权限
  checkLocationPermission() {
    const that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting && res.authSetting['scope.userLocation']) {
          that.setData({
            canGetLocation: true,
            locationGranted: true // 已获取权限
          });
          that.getLocation();
        } else {
          that.setData({
            canGetLocation: false,
            locationGranted: false // 未获取权限
          });
        }
      },
      fail() {
        that.setData({
          canGetLocation: false,
          locationGranted: false // 未获取权限
        });
      }
    });
  },
  
  // 获取位置（用户点击触发）
  getLocation() {
    const that = this;
    if (!this.data.canGetLocation) {
      wx.authorize({
        scope: 'scope.userLocation',
        success() {
          that.setData({
            canGetLocation: true,
            locationGranted: true // 已获取权限
          });
          that.requestLocation();
        },
        fail() {
          wx.showToast({
            title: '需要位置权限才能获取位置',
            icon: 'none'
          });
          that.setData({
            currentLocation: '需要位置权限',
            locationGranted: false // 未获取权限
          });
        }
      });
    } else {
      this.requestLocation();
    }
  },
  
  // 实际请求位置
  requestLocation() {
    wx.showLoading({
      title: '定位中...',
      mask: true
    });
    
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('获取位置成功:', res); // 添加日志
        const { latitude, longitude } = res;
        
        // 确保正确保存经纬度
        this.setData({
          latitude,
          longitude
        });
        // 成功获取位置后设置
      this.setData({
        locationGranted: true // 已获取定位
      });
        
        // 立即获取地址信息
        this.getAddress(latitude, longitude);
      },
      fail: (err) => {
        console.error('获取位置失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '定位失败',
          icon: 'none'
        });
        this.setData({
          currentLocation: '定位失败，请重试',
          locationGranted: false // 定位失败
        });
      }
    });
  },
  
  // 通过经纬度获取地址信息
  getAddress(latitude, longitude) {
    // 发送位置到后端
    this.sendLocationToBackend(latitude, longitude);
    // 添加调试日志
    console.log('开始获取地址:', latitude, longitude);
    
    // 使用您的高德API密钥
    const apiKey = '1a65b37630082ea552ad6547b8f38df4'; 
    
    wx.request({
      url: `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude},${latitude}&radius=1000&extensions=base`,
      success: (res) => {
        wx.hideLoading();
        console.log('高德API响应:', res.data); // 添加调试日志
        
        if (res.data && res.data.status === '1' && res.data.regeocode) {
          // 提取地址信息
          const address = this.extractAddress(res.data.regeocode);
          
          // 确保更新currentLocation
          this.setData({
            currentLocation: address.name || '位置获取成功'
          });
          
        } else {
          console.warn('高德API返回状态异常:', res.data);
          this.setData({
            currentLocation: '位置获取成功'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取地址失败', err);
        this.setData({
          currentLocation: '位置服务暂时不可用'
        });
      }
    });
  },

  // 新增方法：提取详细地址信息
  extractAddress(regeocode) {
    if (!regeocode || !regeocode.addressComponent) {
      console.warn('无地址组件信息');
      return { name: '位置获取成功' };
    }
    
    const comp = regeocode.addressComponent;
    let name = '';
    
    // 1. 尝试获取小区名称
    if (comp.neighborhood && comp.neighborhood.name) {
      name = comp.neighborhood.name;
    } 
    // 2. 尝试获取道路+门牌号
    else if (comp.streetNumber && comp.streetNumber.street) {
      name = comp.streetNumber.street;
      if (comp.streetNumber.number) {
        name += comp.streetNumber.number;
      }
    }
    // 3. 尝试获取乡镇/街道
    else if (comp.township) {
      name = comp.township;
    }
    // 4. 尝试获取区县
    else if (comp.district) {
      name = comp.district;
    }
    // 5. 作为最后手段，使用格式化地址
    else if (regeocode.formatted_address) {
      name = regeocode.formatted_address;
    } else {
      name = '位置获取成功';
    }
    
    // 截断过长的地址
    name = name.length > 15 ? name.substring(0, 15) + '...' : name;
    
    return {
      name,
      province: comp.province || '',
      city: comp.city || '',
      district: comp.district || '',
      township: comp.township || ''
    };
  },

// 发送位置信息到后端
sendLocationToBackend(latitude, longitude) {
  console.log('发送位置到后端:', latitude, longitude);
  
  this.setData({ 
    isLoading: true,
    noDataFlag: false // 重置无数据标志
  });
  
  wx.request({
    url: 'http://node3-cn-hz-cu.haoyue.ltd:10086/getParentsList',
    method: 'GET',
    data: {
      lat: latitude,
      lon: longitude
    },
    success: (res) => {
      console.log('位置信息发送成功', res.data);
      if (res.data && res.data.code === 200) {
        const studentList = res.data.data;
        const noData = studentList.length === 0;
        
        this.setData({
          originalStudents: studentList, // 保存原始列表
          filteredStudents: studentList, // 初始显示全部
          isLoading: false,
          noDataFlag: noData
        });
        
        // 应用当前筛选条件
        this.filterStudents();
      } else {
        console.error('接口返回错误:', res.data.msg);
        this.setData({ 
          isLoading: false,
          noDataFlag: true
        });
      }
    },
    fail: (err) => {
      console.error('位置信息发送失败', err);
      this.setData({ 
        isLoading: false,
        noDataFlag: true
      });
    }
  });
},
  
  // 提取简洁地址
  extractShortAddress(regeocode) {
    if (!regeocode || !regeocode.addressComponent) return '位置获取成功';
    
    const comp = regeocode.addressComponent;
    let shortAddress = '';
    
    if (comp.district) shortAddress += comp.district;
    if (comp.township) shortAddress += comp.township;
    if (comp.street) shortAddress += comp.street;
    if (comp.streetNumber) shortAddress += comp.streetNumber;
    
    // 如果地址过长，截取前15个字符
    return shortAddress.length > 15 ? shortAddress.substring(0, 15) + '...' : shortAddress;
  },
  
  // 筛选器变化事件
  subjectChange(e) {
    this.setData({
      subjectIndex: e.detail.value
    });
    this.filterStudents();
  },
  
  gradeChange(e) {
    this.setData({
      gradeIndex: e.detail.value
    });
    this.filterStudents();
  },
  
  distanceChange(e) {
    this.setData({
      distanceIndex: e.detail.value
    });
    this.filterStudents();
  },
  
  salaryChange(e) {
    this.setData({
      salaryIndex: e.detail.value
    });
    this.filterStudents();
  },
  
  // 筛选学生
  filterStudents() {
    const {
      subjectIndex,
      gradeIndex,
      distanceIndex,
      salaryIndex,
      originalStudents
    } = this.data;
    
    // 如果没有原始数据，直接返回
    if (originalStudents.length === 0) {
      this.setData({
        filteredStudents: [],
        noDataFlag: true
      });
      return;
    }
    
    let filteredList = [...originalStudents];
    
    // 科目筛选（保持不变）
    if (subjectIndex > 0) {
      const selectedSubject = this.data.subjectList[subjectIndex];
      filteredList = filteredList.filter(student => 
        student.subjects && student.subjects.includes(selectedSubject)
      );
    }
    
    // 修改：年级筛选（支持范围筛选）
    if (gradeIndex > 0) {
      const selectedGrade = this.data.gradeList[gradeIndex];
      
      // 定义各学段包含的年级
      const gradeRanges = {
        '小学': ['小一', '小二', '小三', '小四', '小五', '小六'],
        '初中': ['初一', '初二', '初三'],
        '高中': ['高一', '高二', '高三'],
        '大学': ['大一', '大二', '大三', '大四', '研一','研二']
      };
      
      // 获取该学段包含的所有年级
      const includedGrades = gradeRanges[selectedGrade] || [selectedGrade];
      
      filteredList = filteredList.filter(student => 
        student.child_grade && includedGrades.includes(student.child_grade)
      );
    }
    
    // 距离筛选（保持不变）
    if (distanceIndex > 0) {
      let maxDistance;
      switch (this.data.distanceList[distanceIndex]) {
        case '1公里内':
          maxDistance = 1;
          break;
        case '3公里内':
          maxDistance = 3;
          break;
        case '5公里内':
          maxDistance = 5;
          break;
        case '10公里内':
          maxDistance = 10;
          break;
        default:
          maxDistance = Infinity;
      }
      
      filteredList = filteredList.filter(student => 
        parseFloat(student.distance) <= maxDistance
      );
    }
    
    // 薪资筛选（保持不变）
    if (salaryIndex > 0) {
      let minSalary = 0;
      let maxSalary = Infinity;
      
      switch (this.data.salaryList[salaryIndex]) {
        case '50元以下':
          maxSalary = 50;
          break;
        case '50-100元':
          minSalary = 50;
          maxSalary = 100;
          break;
        case '100-200元':
          minSalary = 100;
          maxSalary = 200;
          break;
        case '200元以上':
          minSalary = 200;
          break;
      }
      
      filteredList = filteredList.filter(student => {
        const salary = parseFloat(student.salary);
        return salary >= minSalary && salary < maxSalary;
      });
    }
    
    // 更新筛选后的列表
    this.setData({
      filteredStudents: filteredList,
      noDataFlag: filteredList.length === 0
    });
  },
  
  // 添加清除单个筛选条件的方法
clearFilter(e) {
  const type = e.currentTarget.dataset.type;
  const indexMap = {
    'subject': 'subjectIndex',
    'grade': 'gradeIndex',
    'distance': 'distanceIndex',
    'salary': 'salaryIndex'
  };
  
  if (indexMap[type]) {
    this.setData({
      [indexMap[type]]: 0
    }, () => {
      // 确保状态更新后执行筛选
      this.filterStudents();
    });
  }
},

// 添加清除所有筛选条件的方法
clearAllFilters() {
  this.setData({
    subjectIndex: 0,
    gradeIndex: 0,
    distanceIndex: 0,
    salaryIndex: 0
  }, () => {
    // 确保状态更新后执行筛选
    this.filterStudents();
  });
},
  viewDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/student/detail?id=${id}`,
    });
  },
  
  // 联系学生
  sendMessage(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/chat/index?id=${id}`,
    });
  },
  //
  handleGO(){
    wx.navigateTo({
      url: '/pages/profile/profile',
    })
  },
  handleGOw(){
    wx.navigateTo({
      url: '/pages/order/order',
    })
  },
  handleGO2(){
    wx.navigateTo({
      url: '/pages/introduction/introduction',
    })
  },
  handleGO3(){
    wx.navigateTo({
      url: '/pages/studentdetail/studentdetail',
    })
  },
    handleGO4(){
      wx.navigateTo({
        url: '/pages/contact/contact',
      })
    }

});